package com.igeek.d0617;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhiyu
 * @Date:17:04
 * @DESC:
 */
public class Test2 {
    private static int[] arr = new int[1000];
    private static Lock lock = new ReentrantLock(true);
    private static int count = 0;
    private static int result=0;
    private static int result1=0;
    public static void main(String[] args) {
        int[] ints = randomArr();
        new Thread(()->{
            for (int i:ints) {
                result1+=i;
            }
            System.out.println("result1 = " + result1);
        }).start();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
            System.out.println("result = " + result);
        });
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    Integer sum = sum();
                    lock.lock();
                    result+=sum;
                    lock.unlock();
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            },"线程"+i).start();
        }
    }
    public static int[] randomArr(){
        Random random = new Random();
        for (int i = 0; i < 1000; i++) {
            int x = random.nextInt(100);
            arr[i]=x;
        }
        return arr;
    }
    public static Integer sum(){
        lock.lock();
        int sum = 0;
        try {
            while (count < 1000) {
                for (int i = count; i < Math.min(count + 200, 1000); i++) {
                    sum += arr[i];
                }
                count += 200;
                return sum;
            }
        } finally {
            lock.unlock();
        }
        return sum;
    }
}